// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaeAudioPipeDataHandleThread.h"
#include "../cae_agent/CaeSocketAgent.h"

CaeAudioPipeDataHandleThread::CaeAudioPipeDataHandleThread(CaeDataPipe* pipe)
{
    m_threadStatus = CAE_THREAD_STATUS_NEW;
    m_audioData = pipe;
    m_lastTime = { 0, 0 };
    m_audioPktCountPerSeconds = 0;
}

CaeAudioPipeDataHandleThread::~CaeAudioPipeDataHandleThread()
{
    m_audioData->ClearPipeData();
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
    LOGI("CaeAudioPipeDataHandleThread destroy ok.");
}

void CaeAudioPipeDataHandleThread::Run()
{
    char threadName[] = "AudioPipeHandle";
    prctl(PR_SET_NAME, threadName);
    LOGI("CaeAudioPipeDataHandleThread run.");

    if (m_audioData == nullptr) {
        LOGE("Run failed, dataPipe is null.");
        return;
    }

    while (m_threadStatus == CAE_THREAD_STATUS_RUNNING) {
        CaePipeData *pipeData = m_audioData->GetPipeData();
        if (pipeData != nullptr && pipeData->GetLen() > 0) {
            int ret = CaeSocketAgent::GetInstance().Send((void *) pipeData->GetBuffer(),
                                                         pipeData->GetLen());
            if (ret < 0) {
                LOGD("HandleAudioPipeData, send failed.");
            }

            delete pipeData;
            pipeData = nullptr;
#if DEBUG_STAT_PKT
            if (m_lastTime.tv_sec == 0 && m_lastTime.tv_usec == 0) {
                gettimeofday(&m_lastTime, NULL);
            } else {
                struct timeval curTime = { 0, 0 };
                gettimeofday(&curTime, NULL);

                if (curTime.tv_sec - m_lastTime.tv_sec < 1) {
                    m_audioPktCountPerSeconds = m_audioPktCountPerSeconds + 1;
                } else {
                    LOGI("Send audio pkt to client SDK per seconds: %d.", m_audioPktCountPerSeconds);
                    m_audioPktCountPerSeconds = 0;
                }
                gettimeofday(&m_lastTime, NULL);
            }
#endif
        } else {
            if (pipeData != nullptr) {
                delete pipeData;
                pipeData = nullptr;
            }
        }
        usleep(1000);
    }
    m_threadStatus = CAE_THREAD_STATUS_EXIT;
    LOGI("CaeAudioPipeDataHandleThread exit.");
}